package com.scheduling.product.controller;

import com.scheduling.common.result.Result;
import com.scheduling.product.dto.OperationDTO;
import com.scheduling.product.entity.Operation;
import com.scheduling.product.service.OperationService;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 工序管理控制器
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@Slf4j
@RestController
@RequestMapping("/api/operation")
@Tag(name = "工序管理", description = "工序信息的增删改查操作")
@RequiredArgsConstructor
public class OperationController {

    private final OperationService operationService;

    @io.swagger.v3.oas.annotations.Operation(summary = "根据工艺路线ID获取工序列表", description = "获取指定工艺路线的所有工序，包含原料信息")
    @GetMapping("/route/{routeId}")
    public Result<List<OperationDTO>> getOperationsByRouteId(
            @Parameter(description = "工艺路线ID", required = true) @PathVariable String routeId) {
        try {
            List<OperationDTO> operations = operationService.getOperationsByRouteId(routeId);
            return Result.success(operations);
        } catch (Exception e) {
            log.error("根据工艺路线ID获取工序列表失败：{}", e.getMessage(), e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "根据ID获取工序详情", description = "根据工序ID获取详细信息，包含原料信息")
    @GetMapping("/{operationId}")
    public Result<OperationDTO> getOperationById(
            @Parameter(description = "工序ID", required = true) @PathVariable String operationId) {
        try {
            OperationDTO operationDTO = operationService.getOperationDetailById(operationId);
            return Result.success(operationDTO);
        } catch (Exception e) {
            log.error("获取工序详情失败：{}", e.getMessage(), e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "添加工序", description = "为工艺路线添加新的工序")
    @PostMapping
    public Result<String> addOperation(@Validated @RequestBody OperationDTO operationDTO) {
        try {
            boolean success = operationService.addOperation(operationDTO);
            if (success) {
                return Result.success("添加成功");
            } else {
                return Result.error("添加失败");
            }
        } catch (Exception e) {
            log.error("添加工序失败：{}", e.getMessage(), e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "更新工序", description = "更新工序信息")
    @PutMapping
    public Result<String> updateOperation(@Validated @RequestBody OperationDTO operationDTO) {
        try {
            boolean success = operationService.updateOperation(operationDTO);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新工序失败：{}", e.getMessage(), e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "删除工序", description = "根据ID删除工序，会同时删除原料关联")
    @DeleteMapping("/{operationId}")
    public Result<String> deleteOperation(
            @Parameter(description = "工序ID", required = true) @PathVariable String operationId) {
        try {
            boolean success = operationService.deleteOperation(operationId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除工序失败：{}", e.getMessage(), e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "批量删除工序", description = "根据ID列表批量删除工序")
    @DeleteMapping("/batch")
    public Result<String> deleteOperations(@RequestBody List<String> operationIds) {
        try {
            boolean success = operationService.deleteOperations(operationIds);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除工序失败：{}", e.getMessage(), e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "根据机器类型ID查询工序", description = "获取需要指定机器类型的工序列表")
    @GetMapping("/machine-type/{machineTypeId}")
    public Result<List<Operation>> getOperationsByMachineTypeId(
            @Parameter(description = "机器类型ID", required = true) @PathVariable String machineTypeId) {
        try {
            List<Operation> operations = operationService.getOperationsByMachineTypeId(machineTypeId);
            return Result.success(operations);
        } catch (Exception e) {
            log.error("根据机器类型ID查询工序失败：{}", e.getMessage(), e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "检查工序编号是否存在", description = "检查工序编号在工艺路线内是否已被使用")
    @GetMapping("/check-code")
    public Result<Boolean> checkOperationCodeExists(
            @Parameter(description = "工艺路线ID", required = true) @RequestParam String routeId,
            @Parameter(description = "工序编号", required = true) @RequestParam String operationCode,
            @Parameter(description = "排除的工序ID（更新时使用）") @RequestParam(required = false) String excludeId) {
        try {
            boolean exists = operationService.checkOperationCodeExists(routeId, operationCode, excludeId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查工序编号失败：{}", e.getMessage(), e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }

    @io.swagger.v3.oas.annotations.Operation(summary = "检查工序序号是否存在", description = "检查工序序号在工艺路线内是否已被使用")
    @GetMapping("/check-sequence")
    public Result<Boolean> checkSequenceNoExists(
            @Parameter(description = "工艺路线ID", required = true) @RequestParam String routeId,
            @Parameter(description = "工序序号", required = true) @RequestParam Integer sequenceNo,
            @Parameter(description = "排除的工序ID（更新时使用）") @RequestParam(required = false) String excludeId) {
        try {
            boolean exists = operationService.checkSequenceNoExists(routeId, sequenceNo, excludeId);
            return Result.success(exists);
        } catch (Exception e) {
            log.error("检查工序序号失败：{}", e.getMessage(), e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }
} 